package br.ufc.dc.redes.proxy;

import java.net.*;
import java.io.*;
import java.util.*;

import javax.xml.ws.handler.Handler;

public class ProxyCache {

	public static void handle(Socket client) throws UnknownHostException,
			IOException {
		Socket server = null;
		HttpRequest request = null;
		HttpResponse response = null;
		/*
		 * Requisi��o do processo. Se existir excess�es , retorna e
		 * finaliza a thread. Isso significa que o cliente espera pelo while ate
		 * da timeout
		 */

		/* Ler requisi��o */
		request = adquireRequestFromClient(client);
		System.out.println("Sending request to server...");
		server = sendRequestToServer(request);
		System.out.println("Request sent");
		response = getResponseFromServer(server);
		System.out.println("Server answered w/ sucess");
		sendResponseToClient(client, response);
		System.out.println("Server response sent to client.");
		
		client.close();
		server.close();
	}

	private static void sendResponseToClient(Socket client,
			HttpResponse response) throws IOException {
		DataOutputStream toClient = new DataOutputStream(
				client.getOutputStream());
		//System.out.println(r);
		toClient.writeBytes(response.toString());
		toClient.write(response.getBody());
	}

	private static HttpResponse getResponseFromServer(Socket server)
			throws IOException {
		HttpResponse response;
		DataInputStream fromServer = new DataInputStream(
				server.getInputStream());

		response = new HttpResponse(fromServer);
		return response;
	}

	private static Socket sendRequestToServer(HttpRequest request)
			throws UnknownHostException, IOException {
		Socket server;
		server = new Socket(request.getHost(), request.getPort());
		DataOutputStream toServer = new DataOutputStream(
				server.getOutputStream());
		toServer.writeBytes(request.toString());
		return server;
	}

	private static HttpRequest adquireRequestFromClient(Socket client)
			throws IOException {
		HttpRequest request;
		BufferedReader fromClient = new BufferedReader(new InputStreamReader(
				client.getInputStream()));

		System.out.println("Reading request...");
		request = new HttpRequest(fromClient);
		System.out.println("Got request...");
		return request;
	}
}

	
	
